import {getUserInfo} from "../../../../api/userInfo"
import {createRepair} from "../../../../api/repair"
import {formatTime} from "../../../../utils/utils"

const app = getApp()
const {Toast} = app.globalData

Page({

  /**
   * 页面的初始数据
   */
  data: {
    phoneNumber:String,
    address:String,
    notes:"",
    appointmentTime:"请选择上门时间",
    selectedService:String,
    showPopup:false,
    currentDate: new Date().getTime(),
    minDate:new Date().getTime(),
    maxDate:new Date().getTime() + 1000*60*60*24*7,
    formatter(type, value) {
      if (type === "year") {
        return `${value}年`;
      }
      if (type === 'day') {
        return `${value}日`;
      }
      if (type === 'month') {
        return `${value}月`;
      }
      if (type === 'hour'){
        return `${value}时`
      }
      if (type === "minute") {
        return `${value}分`;
      }
    },
  },

  async onLoad(options) {
    // 获取用户信息
    let userInfo = await getUserInfo()
    // console.log(userInfo)
    let {phoneNumber,address,ownerName,_id} = userInfo

    this.setData({
      selectedService:options.service,
      phoneNumber,
      address,
      ownerName,
      id:_id
    })
  },

  controlPopup(){
    this.setData({
      showPopup:!this.data.showPopup
    })
  },

  onInput(event) {
    this.setData({
      currentDate: event.detail,
    });
  },

  confirmAppointmentTime(e){
    let time = new Date(e.detail)

    let year = time.getFullYear()
    let month = time.getMonth() + 1
    let day = time.getDate()
    let hour = time.getHours()
    let minute = time.getMinutes()

    this.setData({
      appointmentTime:year + "年" + month + "月" + day + "日" + hour + "时",
      showPopup:!this.data.showPopup
    })
  },

  // 提交订单
  async submit(){
    Toast.loading("提交中...")
    
    let {selectedService,address,phoneNumber,appointmentTime,notes,ownerName,id,} = this.data
    let createdTime = formatTime(Date.now())
    let ret = await createRepair({
      service:selectedService,
      targetLocation:address,
      contactNumber:phoneNumber,
      orderer:ownerName,
      ordererId:id,
      appointmentTime,
      notes,
      state:"订单已创建",
      createdTime
    })

    if(ret.code == 201){
      Toast.success("提交成功")

      wx.navigateBack({
        delta:2,
      }
      )
    }else{
      Toast.fail("提交失败")
    }
  }
})